package be.kul.osgi.ds.socketcommunication;

import java.io.*;
import java.net.*;
 
public class ServerThread implements Runnable {
 
    //protected DatagramSocket socket = null;
    protected BufferedReader in = null;
    protected Sock sock;
    protected MulticastSocket ms;
    
    public ServerThread(Sock s) throws IOException {
    	this("QuoteServerThread", s);
    }
 
    public ServerThread(String name, Sock s) throws IOException {
        //socket = new DatagramSocket(4567);
    	sock = s;
        InetAddress group = InetAddress.getByName(sock.group);
    	//InetAddress group = InetAddress.getByName("224.0.0.123");
        ms = new MulticastSocket(sock.port);
        ms.joinGroup(group);
    }
 
    public void run() {
    	System.out.println("Thread1 started");
        while (true) {
            try {
                byte[] buf = new byte[2048];
 
                    // receive request
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                ms.receive(packet);
                String received = new String(packet.getData(), 0, packet.getLength());
                //String sender = packet.getAddress().getCanonicalHostName();
                String sender = packet.getAddress().getHostAddress();
                int sendersocket = packet.getPort();
                sock.messagereceived(received, sender, sendersocket);
                //System.out.println("@ServerThread : received message!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
      //  socket.close();
    }
}
